// BoLe HR Platform - 求职者功能管理

class CandidateManager {
    constructor() {
        this.currentTab = 'profile';
        this.jobs = [];
        this.applications = [];
        this.resumes = [];
        this.profile = null;
    }

    init() {
        if (!authManager.requireCandidate()) return;
        
        // 加载初始数据
        this.loadProfile();
        this.loadAnalytics();
        this.bindEvents();
    }

    bindEvents() {
        // 职位搜索
        const jobKeywords = document.getElementById('jobKeywords');
        if (jobKeywords) {
            jobKeywords.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchJobs();
                }
            });
        }
    }

    async loadProfile() {
        try {
            // 这里应该调用获取候选人档案的API
            // const profile = await api.getCandidateProfile();
            // this.profile = profile;
            // this.fillProfileForm(profile);
        } catch (error) {
            console.error('Failed to load profile:', error);
        }
    }

    fillProfileForm(profile) {
        if (!profile) return;

        document.getElementById('fullName').value = profile.full_name || '';
        document.getElementById('phone').value = profile.phone || '';
        document.getElementById('location').value = profile.location || '';
        document.getElementById('currentPosition').value = profile.current_position || '';
        document.getElementById('experienceYears').value = profile.experience_years || 0;
        document.getElementById('skills').value = profile.skills ? profile.skills.join(', ') : '';
        document.getElementById('githubUrl').value = profile.github_url || '';
        document.getElementById('linkedinUrl').value = profile.linkedin_url || '';
    }

    async loadAnalytics() {
        try {
            const analytics = await api.getCandidateAnalytics();
            this.updateAnalyticsDisplay(analytics);
        } catch (error) {
            console.error('Failed to load analytics:', error);
        }
    }

    updateAnalyticsDisplay(analytics) {
        // 这里可以更新仪表板上的分析数据显示
        console.log('Analytics data:', analytics);
    }

    async searchJobs() {
        const keywords = document.getElementById('jobKeywords').value.trim();
        const experienceLevel = document.getElementById('jobExperienceLevel').value;
        const location = document.getElementById('jobLocation').value.trim();

        const searchData = {
            keywords: keywords || undefined,
            experience_level: experienceLevel || undefined,
            location: location || undefined,
            limit: 20
        };

        const jobResults = document.getElementById('jobSearchResults');
        showLoading(jobResults);

        try {
            const jobs = await api.searchJobs(searchData);
            this.jobs = jobs;
            this.renderJobResults(jobs);
        } catch (error) {
            console.error('Failed to search jobs:', error);
            showError(jobResults, '搜索职位失败');
        }
    }

    renderJobResults(jobs) {
        const jobResults = document.getElementById('jobSearchResults');
        
        if (jobs.length === 0) {
            showEmpty(jobResults, '未找到匹配的职位，请尝试其他关键词');
            return;
        }

        jobResults.innerHTML = jobs.map(job => `
            <div class="list-item">
                <div class="item-header">
                    <div>
                        <h4 class="item-title">${job.title}</h4>
                        <p class="item-subtitle">${job.company.name}</p>
                    </div>
                    <div class="item-actions">
                        <button class="btn btn-sm btn-outline" onclick="candidateManager.viewJobDetails(${job.id})">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="candidateManager.applyForJob(${job.id})">
                            <i class="fas fa-paper-plane"></i> 申请
                        </button>
                    </div>
                </div>
                <div class="item-meta">
                    <span class="meta-item">
                        <i class="fas fa-map-marker-alt"></i>
                        ${job.location || '未指定'}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-briefcase"></i>
                        ${job.experience_level}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-dollar-sign"></i>
                        ${job.salary_range || '面议'}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-clock"></i>
                        ${job.employment_type}
                    </span>
                </div>
                <div class="item-content">
                    <p>${job.description.substring(0, 200)}${job.description.length > 200 ? '...' : ''}</p>
                    <div class="job-requirements">
                        <strong>技能要求：</strong>
                        ${job.requirements.map(req => `<span class="skill-tag">${req}</span>`).join('')}
                    </div>
                </div>
            </div>
        `).join('');
    }

    async loadApplications() {
        const applicationsList = document.getElementById('applicationsList');
        showLoading(applicationsList);

        try {
            const applications = await api.getMyApplications();
            this.applications = applications;
            this.renderApplicationsList(applications);
        } catch (error) {
            console.error('Failed to load applications:', error);
            showError(applicationsList, '加载申请失败');
        }
    }

    renderApplicationsList(applications) {
        const applicationsList = document.getElementById('applicationsList');
        
        if (applications.length === 0) {
            showEmpty(applicationsList, '暂无申请记录，去搜索心仪的职位吧');
            return;
        }

        applicationsList.innerHTML = applications.map(app => `
            <div class="list-item">
                <div class="item-header">
                    <div>
                        <h4 class="item-title">${app.job_position.title}</h4>
                        <p class="item-subtitle">${app.job_position.company.name}</p>
                    </div>
                    <div class="item-actions">
                        <button class="btn btn-sm btn-outline" onclick="candidateManager.viewJobDetails(${app.job_position.id})">
                            <i class="fas fa-eye"></i> 查看职位
                        </button>
                        ${app.hr_feedback ? `
                            <button class="btn btn-sm btn-info" onclick="candidateManager.viewFeedback('${app.hr_feedback}')">
                                <i class="fas fa-comment"></i> 反馈
                            </button>
                        ` : ''}
                    </div>
                </div>
                <div class="item-meta">
                    <span class="meta-item">
                        <i class="fas fa-calendar"></i>
                        ${formatDate(app.applied_at)}
                    </span>
                    ${app.match_score ? `
                        <span class="meta-item">
                            <i class="fas fa-star"></i>
                            匹配度: ${Math.round(app.match_score * 100)}%
                        </span>
                    ` : ''}
                    <span class="status-badge status-${app.status}">
                        ${this.getStatusText(app.status)}
                    </span>
                </div>
            </div>
        `).join('');
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '待审核',
            'screening': '筛选中',
            'interview': '面试邀请',
            'hired': '已录取',
            'rejected': '未通过'
        };
        return statusMap[status] || status;
    }

    async loadResumes() {
        const resumesList = document.getElementById('resumesList');
        showLoading(resumesList);

        try {
            const resumes = await api.getMyResumes();
            this.resumes = resumes;
            this.renderResumesList(resumes);
        } catch (error) {
            console.error('Failed to load resumes:', error);
            showError(resumesList, '加载简历失败');
        }
    }

    renderResumesList(resumes) {
        const resumesList = document.getElementById('resumesList');
        
        if (resumes.length === 0) {
            showEmpty(resumesList, '暂无简历，上传您的简历开始求职之旅');
            return;
        }

        resumesList.innerHTML = resumes.map(resume => `
            <div class="list-item">
                <div class="item-header">
                    <div>
                        <h4 class="item-title">${resume.original_filename}</h4>
                        ${resume.score ? `
                            <div class="resume-score">
                                <span class="score-badge">评分: ${Math.round(resume.score)}/100</span>
                            </div>
                        ` : ''}
                    </div>
                    <div class="item-actions">
                        <button class="btn btn-sm btn-outline" onclick="candidateManager.viewResumeAnalysis(${resume.id})">
                            <i class="fas fa-chart-line"></i> 分析
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="candidateManager.optimizeResume(${resume.id})">
                            <i class="fas fa-magic"></i> 优化
                        </button>
                    </div>
                </div>
                <div class="item-meta">
                    <span class="meta-item">
                        <i class="fas fa-calendar"></i>
                        ${formatDate(resume.created_at)}
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-file"></i>
                        ${resume.original_filename.split('.').pop().toUpperCase()}
                    </span>
                </div>
            </div>
        `).join('');
    }

    uploadResume() {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-upload"></i> 上传简历</h3>
            <div class="upload-area">
                <input type="file" id="resumeFile" accept=".pdf,.doc,.docx" style="display: none;">
                <div class="upload-prompt" onclick="document.getElementById('resumeFile').click()">
                    <i class="fas fa-cloud-upload-alt fa-3x"></i>
                    <p>点击选择简历文件</p>
                    <small>支持 PDF, DOC, DOCX 格式，大小不超过 10MB</small>
                </div>
            </div>
            <div class="upload-tips">
                <h4>简历优化建议：</h4>
                <ul>
                    <li>确保联系信息准确完整</li>
                    <li>突出相关技能和项目经验</li>
                    <li>使用清晰的章节结构</li>
                    <li>避免拼写和语法错误</li>
                </ul>
            </div>
        `;

        document.getElementById('resumeFile').addEventListener('change', (e) => this.handleResumeUpload(e));
        showModal();
    }

    async handleResumeUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        // 文件大小检查
        const maxSize = 10 * 1024 * 1024; // 10MB
        if (file.size > maxSize) {
            showToast('文件大小不能超过 10MB', 'error');
            return;
        }

        const uploadArea = document.querySelector('.upload-area');
        uploadArea.innerHTML = `
            <div class="loading">
                <i class="fas fa-spinner fa-spin fa-2x"></i>
                <p>正在上传和分析简历...</p>
            </div>
        `;

        try {
            const formData = new FormData();
            formData.append('file', file);

            const result = await api.uploadResume(formData);
            
            showToast('简历上传成功！', 'success');
            closeModal();
            
            // 刷新简历列表
            if (this.currentTab === 'resume') {
                this.loadResumes();
            }

        } catch (error) {
            console.error('Resume upload failed:', error);
            showToast(error.message || '简历上传失败', 'error');
            
            // 恢复上传界面
            uploadArea.innerHTML = `
                <div class="upload-prompt" onclick="document.getElementById('resumeFile').click()">
                    <i class="fas fa-cloud-upload-alt fa-3x"></i>
                    <p>点击重新选择文件</p>
                    <small>上传失败，请重试</small>
                </div>
            `;
        }
    }

    async applyForJob(jobId) {
        // 检查是否有简历
        if (this.resumes.length === 0) {
            showToast('请先上传简历再申请职位', 'warning');
            showCandidateTab('resume');
            return;
        }

        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-paper-plane"></i> 申请职位</h3>
            <form id="applyJobForm">
                <div class="form-group">
                    <label for="selectResume">选择简历</label>
                    <select id="selectResume" name="resume_id" required>
                        <option value="">请选择要使用的简历</option>
                        ${this.resumes.map(resume => `
                            <option value="${resume.id}">
                                ${resume.original_filename} 
                                ${resume.score ? `(评分: ${Math.round(resume.score)})` : ''}
                            </option>
                        `).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label for="coverLetter">求职信 (可选)</label>
                    <textarea id="coverLetter" name="cover_letter" rows="5" 
                              placeholder="简要介绍您的优势和对该职位的兴趣..."></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> 提交申请
                    </button>
                </div>
                <input type="hidden" name="job_position_id" value="${jobId}">
            </form>
        `;

        document.getElementById('applyJobForm').addEventListener('submit', (e) => this.handleJobApplication(e));
        showModal();
    }

    async handleJobApplication(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        
        const applicationData = {
            job_position_id: parseInt(formData.get('job_position_id')),
            resume_id: parseInt(formData.get('resume_id')),
            cover_letter: formData.get('cover_letter')
        };

        try {
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
            submitBtn.disabled = true;

            await api.applyForJob(applicationData);
            showToast('申请提交成功！', 'success');
            closeModal();

        } catch (error) {
            console.error('Job application failed:', error);
            showToast(error.message || '申请提交失败', 'error');
        } finally {
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 提交申请';
            submitBtn.disabled = false;
        }
    }

    async optimizeResume(resumeId) {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-magic"></i> 简历优化</h3>
            <div class="optimization-options">
                <div class="form-group">
                    <label for="targetJob">目标职位 (可选)</label>
                    <select id="targetJob">
                        <option value="">通用优化</option>
                        ${this.jobs.slice(0, 10).map(job => `
                            <option value="${job.id}">${job.title} - ${job.company.name}</option>
                        `).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label for="targetSkills">目标技能 (可选)</label>
                    <input type="text" id="targetSkills" placeholder="用逗号分隔，如：Python, React, SQL">
                </div>
                <button class="btn btn-primary" onclick="candidateManager.performOptimization(${resumeId})">
                    <i class="fas fa-magic"></i> 开始优化
                </button>
            </div>
            <div id="optimizationResult" style="display: none;">
                <!-- 优化结果将显示在这里 -->
            </div>
        `;

        showModal();
    }

    async performOptimization(resumeId) {
        const targetJobId = document.getElementById('targetJob').value;
        const targetSkills = document.getElementById('targetSkills').value;

        const optimizationData = {
            target_job_id: targetJobId ? parseInt(targetJobId) : null,
            target_skills: targetSkills ? targetSkills.split(',').map(s => s.trim()).filter(s => s) : null
        };

        const optionsDiv = document.querySelector('.optimization-options');
        optionsDiv.innerHTML = `
            <div class="loading">
                <i class="fas fa-spinner fa-spin fa-2x"></i>
                <p>正在优化简历...</p>
            </div>
        `;

        try {
            const result = await api.optimizeResume(resumeId, optimizationData);
            this.showOptimizationResult(result);
        } catch (error) {
            console.error('Resume optimization failed:', error);
            optionsDiv.innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>优化失败，请重试</p>
                </div>
            `;
        }
    }

    showOptimizationResult(result) {
        const resultDiv = document.getElementById('optimizationResult');
        resultDiv.style.display = 'block';
        resultDiv.innerHTML = `
            <div class="optimization-summary">
                <h4>优化结果</h4>
                <div class="score-comparison">
                    <div class="score-item">
                        <span class="score-label">原始评分</span>
                        <span class="score-value">${Math.round(result.original_score)}</span>
                    </div>
                    <i class="fas fa-arrow-right"></i>
                    <div class="score-item">
                        <span class="score-label">优化后评分</span>
                        <span class="score-value score-improved">${Math.round(result.ats_compatibility_score)}</span>
                    </div>
                </div>
            </div>
            <div class="optimization-details">
                <div class="improvements">
                    <h5><i class="fas fa-check-circle"></i> 改进建议</h5>
                    <ul>
                        ${result.improvements.map(improvement => `<li>${improvement}</li>`).join('')}
                    </ul>
                </div>
                <div class="keywords">
                    <h5><i class="fas fa-tags"></i> 关键词建议</h5>
                    <div class="keyword-tags">
                        ${result.keyword_suggestions.map(keyword => `<span class="skill-tag">${keyword}</span>`).join('')}
                    </div>
                </div>
                <div class="structure">
                    <h5><i class="fas fa-list"></i> 结构建议</h5>
                    <ul>
                        ${result.structure_recommendations.map(rec => `<li>${rec}</li>`).join('')}
                    </ul>
                </div>
            </div>
        `;
    }

    async getJobRecommendations() {
        try {
            const recommendations = await api.getCandidateRecommendations({
                user_id: authManager.currentUser.id,
                recommendation_type: 'jobs'
            });

            this.showRecommendations('职位推荐', recommendations.recommendations);
        } catch (error) {
            console.error('Failed to get job recommendations:', error);
            showToast('获取推荐失败', 'error');
        }
    }

    async getSkillRecommendations() {
        try {
            const recommendations = await api.getCandidateRecommendations({
                user_id: authManager.currentUser.id,
                recommendation_type: 'skills'
            });

            this.showRecommendations('技能推荐', recommendations.recommendations);
        } catch (error) {
            console.error('Failed to get skill recommendations:', error);
            showToast('获取推荐失败', 'error');
        }
    }

    showRecommendations(title, recommendations) {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3><i class="fas fa-lightbulb"></i> ${title}</h3>
            <div class="recommendations-list">
                ${recommendations.map((rec, index) => `
                    <div class="recommendation-item">
                        <h4>${rec.title || `推荐 ${index + 1}`}</h4>
                        <p>${rec.description || rec.content}</p>
                        ${rec.action ? `
                            <button class="btn btn-primary btn-sm">${rec.action}</button>
                        ` : ''}
                    </div>
                `).join('')}
            </div>
        `;

        showModal();
    }

    viewJobDetails(jobId) {
        const job = this.jobs.find(j => j.id === jobId);
        if (!job) {
            showToast('职位信息不存在', 'error');
            return;
        }

        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <h3>${job.title}</h3>
            <div class="job-company">
                <h4>${job.company.name}</h4>
                ${job.company.description ? `<p>${job.company.description}</p>` : ''}
            </div>
            <div class="job-details">
                <div class="job-meta">
                    <div class="meta-item">
                        <i class="fas fa-map-marker-alt"></i>
                        <span>${job.location || '未指定'}</span>
                    </div>
                    <div class="meta-item">
                        <i class="fas fa-briefcase"></i>
                        <span>${job.experience_level}</span>
                    </div>
                    <div class="meta-item">
                        <i class="fas fa-dollar-sign"></i>
                        <span>${job.salary_range || '面议'}</span>
                    </div>
                    <div class="meta-item">
                        <i class="fas fa-clock"></i>
                        <span>${job.employment_type}</span>
                    </div>
                </div>
                <div class="job-description">
                    <h5>职位描述</h5>
                    <p>${job.description}</p>
                </div>
                <div class="job-requirements">
                    <h5>技能要求</h5>
                    <div class="skill-tags">
                        ${job.requirements.map(req => `<span class="skill-tag">${req}</span>`).join('')}
                    </div>
                </div>
            </div>
            <div class="modal-actions">
                <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                <button class="btn btn-primary" onclick="candidateManager.applyForJob(${job.id}); closeModal();">
                    <i class="fas fa-paper-plane"></i> 申请职位
                </button>
            </div>
        `;

        showModal();
    }
    
    // 加载数据分析
    async loadAnalytics() {
        try {
            // 加载概览统计
            const response = await fetch('/api/jh/overview');
            if (response.ok) {
                const stats = await response.json();
                
                // 更新概览数据
                document.getElementById('summaryTotalJobs').textContent = this.formatNumber(stats.total_jobs);
                document.getElementById('summaryTotalCompanies').textContent = this.formatNumber(stats.total_companies);
                document.getElementById('summaryAvgSalary').textContent = stats.avg_salary;
                
                // 模拟热门技能数据
                document.getElementById('summaryTopSkill').textContent = 'Python';
            } else {
                throw new Error('加载失败');
            }
        } catch (error) {
            console.error('加载数据分析失败:', error);
            // 使用模拟数据
            document.getElementById('summaryTotalJobs').textContent = '785,741';
            document.getElementById('summaryTotalCompanies').textContent = '156,892';
            document.getElementById('summaryAvgSalary').textContent = '$89,500';
            document.getElementById('summaryTopSkill').textContent = 'Python';
        }
    }
    
    formatNumber(num) {
        if (typeof num !== 'number') return num;
        return num.toLocaleString();
    }
}

// 求职者标签页切换
function showCandidateTab(tabName) {
    if (!authManager.requireCandidate()) return;
    
    // 更新标签状态
    document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // 显示对应内容
    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
    document.getElementById(`candidate-${tabName}`).classList.add('active');
    
    candidateManager.currentTab = tabName;
    
    // 加载对应数据
    switch(tabName) {
        case 'profile':
            candidateManager.loadProfile();
            break;
        case 'jobs':
            // 职位搜索页面不需要预加载
            break;
        case 'applications':
            candidateManager.loadApplications();
            break;
        case 'resume':
            candidateManager.loadResumes();
            break;
        case 'analytics':
            candidateManager.loadAnalytics();
            break;
        case 'recommendations':
            // 推荐页面不需要预加载
            break;
    }
}

// 全局函数
function searchJobs() {
    candidateManager.searchJobs();
}

function uploadResume() {
    candidateManager.uploadResume();
}

function loadAnalyticsSummary() {
    candidateManager.loadAnalytics();
}

function openJHDashboard() {
    // 在新标签页中打开JH数据分析仪表板
    window.open('jh_subsystem/jh_dashboard.html', '_blank');
}

function getJobRecommendations() {
    candidateManager.getJobRecommendations();
}

function getSkillRecommendations() {
    candidateManager.getSkillRecommendations();
}

function optimizeResume() {
    if (candidateManager.resumes.length === 0) {
        showToast('请先上传简历', 'warning');
        showCandidateTab('resume');
        return;
    }
    
    // 使用第一个简历进行优化
    candidateManager.optimizeResume(candidateManager.resumes[0].id);
}

// 创建全局求职者管理器实例
const candidateManager = new CandidateManager();